package com.ljs.module.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.ftp.Ftp;
import com.ljs.module.common.DataBean;
import com.ljs.module.entity.ConfigProperties;
import com.ljs.module.entity.smartbi.SearchExt;
import com.ljs.module.util.FtpUtil;
import com.ljs.module.util.Util;
import org.apache.commons.net.ftp.FTPFile;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/ftp")
public class FtpController {
    @ResponseBody
    @PostMapping("/init")
    public List<List<String>> init() throws IOException {
        Ftp ftp = FtpUtil.init();
        List<List<String>> ret = new ArrayList<>();
        try {
            List<String> baseUrls = new ArrayList<>(Arrays.asList(new String[]{"22.项目扩展包","Smartbi_ext"})) ;
            String basePath = "/";
            for (String baseUrl : baseUrls) {
                basePath += baseUrl + "/";
            }

            FTPFile[] ftpFiles = ftp.lsFiles(basePath);
            List<String> versions = Arrays.stream(ftpFiles).map(x -> x.getName()).collect(Collectors.toList());
            for (int i = 0; i < versions.size(); i++) {
                if (versions.get(i).equals("PD_Projects")) {
                    String temp = versions.get(0);
                    versions.set(0, versions.get(i));
                    versions.set(i, temp);
                }
            }
            basePath += versions.get(0) + "/";
            ftpFiles = ftp.lsFiles(basePath);
            List<String> branches = Arrays.stream(ftpFiles).map(x -> x.getName()).collect(Collectors.toList());
            ret.add(baseUrls);
            ret.add(versions);
            ret.add(branches);
        } finally {
            FtpUtil.close();
        }
        return ret;
    }

    @ResponseBody
    @PostMapping("/search")
    public Map<String, SearchExt> search(String[] baseUrls, String version, String branch, String searchExt, String[] extensionsExt, String[] configs) throws IOException {
        FtpUtil.init();
        try {
            ConfigProperties configProperties = ConfigProperties.of(configs);
            List<String> cacheFtp = FtpUtil.loadCache(version, branch);
            if (configProperties.isNoFtpCache()) {
                cacheFtp = FtpUtil.cache(baseUrls, version, branch);
            }
            if (!configProperties.isNoFtpCache() && (cacheFtp == null || cacheFtp.size() == 0)) {
                cacheFtp = FtpUtil.cache(baseUrls, version, branch);
            }
            return FtpUtil.searchExt(cacheFtp, searchExt, extensionsExt);
        } finally {
            FtpUtil.close();
        }
    }

    @ResponseBody
    @PostMapping("/download")
    public DataBean download(String ftpPath, String localPath, String fileName) throws IOException {
        Ftp ftp = FtpUtil.init();
        try {
            fileName += ".ext";
            localPath += Util.replaceFileSeparor("/WEB-INF/extensions/") + fileName;
            ftpPath += fileName;
            File file = new File(localPath);
            if (file.exists()) {
                return DataBean.fail("该扩展包已存在，请先去往ext管理删除该扩展包").setReasonCode(1);
            }
            if (!FtpUtil.exist(ftpPath, ftp)) {
                String dir = StrUtil.removeSuffix(ftpPath, fileName);
                List<String> ls = ftp.ls(dir);
                if (ls.size() == 0)
                    return DataBean.fail("找不到该路径下的扩展包" + ftpPath).setReasonCode(2);
                else {
                    List<String> collect = ls.stream().filter(x -> x.endsWith(".ext")).map(x -> x.substring(0, x.lastIndexOf("."))).collect(Collectors.toList());
                    if (collect.size() == 0) {
                        return DataBean.fail("找不到该路径下的扩展包" + ftpPath).setReasonCode(2);
                    } else {
                        return DataBean.fail("找不到该路径下的扩展包" + ftpPath).setReasonCode(3).setData(collect);
                    }
                }
            }
            ftp.download(ftpPath, file);
        } finally {
            FtpUtil.close();
        }
        return DataBean.success().setReasonCode(0).setDesc("下载成功");
    }
}
